package org.ceteca.explica.server.installer;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.installer.Installer;
import org.ceteca.explica.core.ssl.RMISSLClientSocketFactory;
import org.ceteca.explica.core.ssl.RMISSLServerSocketFactory;
import org.ceteca.explica.server.ServerContext;

public class UpdateManager {
	/**
	 * Singleton pattern. Unique instance of the UpdateManager class.
	 */
	private static UpdateManager instance;
	
	private UpdateManager() {
	}
	
	/**
	 * Gets an instance of the UpdateManager class.
	 * @return UpdateManager, the unique instance of the UpdateManager class 
	 * (Singleton pattern).
	 */
	public static UpdateManager getInstance() {
		if (instance == null)
			instance = new UpdateManager();
		
		return instance;
	}
	
	/**
	 * Initializes the installer remote object. Makes the registration and
	 * binding of the remote Installer service.  
	 */
	public void initInstaller() {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        try {
            String name = InterfaceExplica.JNDI_INSTALLER_EXPORT_NAME;
            InstallerImpl ins = new InstallerImpl();

            // Unexport any previous remote installer object
            UnicastRemoteObject.unexportObject(ins, true);
            ServerContext.getInstance().getLogger().
            	info("Installer unexported");


            // Export the installer object to listen in the assigned port
            Installer stub =
                (Installer) UnicastRemoteObject.exportObject(ins, InterfaceExplica.RMI_INSTALLER_EXPORT_PORT, 
                		new RMISSLClientSocketFactory(),
               		 	new RMISSLServerSocketFactory());
            
            ServerContext.getInstance().getLogger().
        		info("Installer exported");

    	    // Create a registry and bind stub in registry.
    	    LocateRegistry.createRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    Registry registry = LocateRegistry.getRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    
    	    ServerContext.getInstance().getLogger().
        		info("Registry located");
            registry.rebind(name, stub);
            ServerContext.getInstance().getLogger().
        		info("Installer bound");
        } catch (Exception e) {
            ServerContext.getInstance().getLogger().
        		error("Installer exception", e);
        }
	}
}
